<script setup lang="ts">
import axios from "axios";
import { ElMessage } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useLogging } from "../stores/logging";
import { BorrowStatusTitle, type BorrowRecord } from "../types/BorrowRecord";
import type { ResultContext } from "../types/ResultContext";

const logging = useLogging();
const borrowList = ref<BorrowRecord[]>([]);

// 从后端根据 userId 获取借阅记录
async function getBorrowing() {
  if (!logging.getUser?.id) {
    ElMessage.error("请先登录");
    return;
  }

  try {
    const res = await axios.get<ResultContext<BorrowRecord[]>>(
      `http://localhost:8080/api/users/${logging.getUser.id}/borrows`,
    );

    borrowList.value = res.data.data;
  } catch (_error) {
    ElMessage.error("借阅记录加载失败");
  }
}

// 还书
async function returnBook(borrow: BorrowRecord) {
  if (!logging.getUser) {
    ElMessage.error("请先登录");
    return;
  }

  try {
    const res = await axios.patch(
      `http://localhost:8080/api/borrows/${borrow.id}/return`,
    );

    if (res.data.code === 0) {
      ElMessage.success("还书成功！");
      await getBorrowing(); // 重新刷新列表
    } else {
      ElMessage.error(res.data.message ?? "还书失败！");
    }
  } catch (_error) {
    ElMessage.error("请求失败，请稍后再试");
  }
}

// 分类借阅记录：当前（借阅中、逾期）和已归还
const activeBorrows = computed(() =>
  borrowList.value.filter(
    b => b.status === "BORROWING" || b.status === "OVERDUE",
  ),
);

const returnedBorrows = computed(() =>
  borrowList.value.filter(b => b.status === "RETURNED"),
);

onMounted(() => {
  void getBorrowing();
});
</script>

<template>
  <div class="borrow-container">
    <div class="page-header">
      <h1>我的借阅</h1>
      <p>查看您当前的借阅状态和历史记录</p>
    </div>

    <!-- 当前借阅记录 -->
    <div class="section-card" v-if="activeBorrows.length > 0">
      <div class="section-header">
        <h3>当前借阅</h3>
        <span class="section-count">{{ activeBorrows.length }} 本</span>
      </div>

      <el-table :data="activeBorrows" style="width: 100%" border>
        <el-table-column
          prop="book.title"
          label="名称"
          align="center"
          width="180"
        />
        <el-table-column
          prop="book.author"
          label="作者"
          align="center"
          width="150"
        />
        <el-table-column label="状态" align="center" width="140">
          <template #default="{ row }: { row: BorrowRecord }">
            <span
              class="book-status"
              :class="{
                'status-borrowing': row.status === 'BORROWING',
                'status-overdue': row.status === 'OVERDUE',
                'status-returned': row.status === 'RETURNED',
              }"
            >
              {{ BorrowStatusTitle[row.status] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="borrowTime"
          label="借阅日期"
          align="center"
          width="180"
        />
        <el-table-column
          prop="deadline"
          label="截止时间"
          align="center"
          width="180"
        >
          <template #default="{ row }">
            <span :class="{ 'overdue-text': row.status === 'OVERDUE' }">
              {{ row.deadline }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="primary" round @click="returnBook(row)"
              >还书</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 历史归还记录 -->
    <div
      class="section-card"
      v-if="returnedBorrows.length > 0"
      style="margin-top: 40px"
    >
      <div class="section-header">
        <h3>历史记录</h3>
        <span class="section-count">{{ returnedBorrows.length }} 本</span>
      </div>

      <el-table :data="returnedBorrows" style="width: 100%" border>
        <el-table-column
          prop="book.title"
          label="名称"
          align="center"
          width="180"
        />
        <el-table-column
          prop="book.author"
          label="作者"
          align="center"
          width="150"
        />
        <el-table-column label="状态" align="center" width="140">
          <template #default="{ row }: { row: BorrowRecord }">
            <span
              class="book-status"
              :class="{
                'status-borrowing': row.status === 'BORROWING',
                'status-overdue': row.status === 'OVERDUE',
                'status-returned': row.status === 'RETURNED',
              }"
            >
              {{ BorrowStatusTitle[row.status] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="borrowTime"
          label="借阅日期"
          align="center"
          width="180"
        />
        <el-table-column prop="deadline" label="截止时间" align="center" />
      </el-table>
    </div>

    <div class="section-card empty-state" v-else>
      <p>暂无借阅记录</p>
    </div>
  </div>
</template>

<style scoped>
@import "@/assets/css/borrowing.css";
</style>
